package com.ocom.webapi.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.WebApiServiceUrl;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.payconfig.schoolphone.SchoolPhoneInfoVo;
import com.ocom.common.utils.excel.EasyExcelUtil;
import com.ocom.common.vo.payconfig.schoolphone.SchoolPhoneInfoVo;
import com.ocom.common.vo.webapi.SchoolPhonePageVo;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.HumanClientService;
import com.ocom.webapi.feign.PayConfigClientService;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
//@PreAuthorize("@pms.hasRole('ROLE_WEB')" )
@Slf4j
public class SchoolPhonePageController {

    @Autowired
    private HumanClientService humanClientService;

    @Autowired
    private PayConfigClientService payConfigClientService;

    @PostMapping(value = WebApiServiceUrl.Url_SchoolPhonePageOnShow)
    public Result schoolPhonePageOnShow(@RequestBody SchoolPhoneInfoVo schoolPhoneInfoVo) {

        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        Long comId = yoCiUser.getComId();
        if (ObjectUtil.isEmpty(schoolPhoneInfoVo.getComId())) {
            schoolPhoneInfoVo.setComId(Math.toIntExact(comId));
        }
        return payConfigClientService.getSchoolPhoneList(schoolPhoneInfoVo);
    }

    @PostMapping(value = WebApiServiceUrl.Url_SchoolPhonePageModify)
    public Result schoolPhonePageModify(@RequestBody SchoolPhoneInfoVo schoolPhoneInfoVo) {
        log.info("校园电话修改{}",schoolPhoneInfoVo.toString());
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        Long comId = yoCiUser.getComId();
        String username = yoCiUser.getUsername();
        if (ObjectUtil.isEmpty(schoolPhoneInfoVo.getComId())) {
            schoolPhoneInfoVo.setComId(Math.toIntExact(comId));
        }
        if (ObjectUtil.isNotEmpty(username)) {
            schoolPhoneInfoVo.setUpdateUser(username);
        }

        return payConfigClientService.updateSchoolPhoneInfo(schoolPhoneInfoVo);
    }

    @PostMapping(value = WebApiServiceUrl.Url_SchoolPhonePageImport)
    public Result schoolPhonePageImport(@RequestParam Long comId, @RequestPart("file") MultipartFile file) throws IOException, InvalidFormatException {

        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
//        Long comId = yoCiUser.getComId();
        String username = yoCiUser.getUsername();

        List<SchoolPhonePageVo> schoolPhonePageVos = EasyExcelUtil.readFromExcel(file.getInputStream(), SchoolPhonePageVo.class, 0);
        List<SchoolPhoneInfoVo> list = schoolPhonePageVos.stream().filter(Objects::nonNull).map(schoolPhonePageVo -> {
            SchoolPhoneInfoVo schoolPhoneInfoVo = new SchoolPhoneInfoVo();
            BeanUtils.copyProperties(schoolPhonePageVo, schoolPhoneInfoVo);
            return schoolPhoneInfoVo;
        }).collect(Collectors.toList());

        Map<String, Object> map = new HashMap<>();
        AtomicInteger count = new AtomicInteger();
        list.forEach(schoolPhoneInfoVo -> {
            String pName = schoolPhoneInfoVo.getPName();
            String pCode = schoolPhoneInfoVo.getPCode();
            map.put("pName", pName);
            map.put("pCode", pCode);
            map.put("comId", comId);
            map.put("page", 0);
            map.put("size", 0);
            Result personInfo = humanClientService.PersonnelGetPersonInfo(map);
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(personInfo.getData()));
            if (jsonObject.getInteger("total") == 0 || ObjectUtil.isEmpty(jsonObject.get("list"))) {
                return;
            }
            JSONArray jsonArray = jsonObject.getJSONArray("list");
            if (ObjectUtil.isEmpty(jsonArray)) {
                schoolPhoneInfoVo.setPId(Math.toIntExact(jsonObject.getLong("pId")));
                schoolPhoneInfoVo.setComId(Math.toIntExact(comId));
                schoolPhoneInfoVo.setUpdateUser(username == null ? schoolPhoneInfoVo.getUpdateUser() : username);
                payConfigClientService.updateSchoolPhoneInfo(schoolPhoneInfoVo);
                count.getAndIncrement();
            } else {
                jsonArray.forEach(json -> {
                    JSONObject object = (JSONObject) json;
                    schoolPhoneInfoVo.setPId(Math.toIntExact(object.getLong("pId")));
                    schoolPhoneInfoVo.setComId(Math.toIntExact(comId));
                    schoolPhoneInfoVo.setUpdateUser(username == null ? schoolPhoneInfoVo.getUpdateUser() : username);
                    payConfigClientService.updateSchoolPhoneInfo(schoolPhoneInfoVo);
                    count.getAndIncrement();
                });
            }
        });
        return ResultUtil.success("处理成功人数：" + count.get());
    }

}